package com.app;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.app.activity.ActivityMine;
import com.app.constant.KeyValue;

import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements BDLocationListener, BaiduMap.OnMapStatusChangeListener {

    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.mMapView)
    MapView mMapView;


    // 定位相关
    private LocationClient mLocClient = null;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private BitmapDescriptor mCurrentMarker;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00FF00;

    private BaiduMap mBaiduMap;


    private Marker mMarkerA;
    private Marker mMarkerB;
    private Marker mMarkerC;
    private Marker mMarkerD;

    private InfoWindow mInfoWindow;


    // 初始化全局 bitmap 信息，不用时及时 recycle
    BitmapDescriptor icon_dot = BitmapDescriptorFactory
            .fromResource(R.mipmap.icon_map_dot);
    private boolean isFirstLoc = true; // 是否首次定位

    private final static int SCANNIN_GREQUEST_CODE = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        //设置是否显示比例尺控件
        mMapView.showScaleControl(false);
        //设置是否显示缩放控件
        mMapView.showZoomControls(false);
        // 地图初始化
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapStatusChangeListener(this);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        View view = LayoutInflater.from(this).inflate(R.layout.item_marker_layout, null, false);
        icon_dot = BitmapDescriptorFactory.fromView(view);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            public boolean onMarkerClick(final Marker marker) {
                final Button button = new Button(getApplicationContext());
                button.setBackgroundResource(R.mipmap.popup);
                final InfoWindow.OnInfoWindowClickListener[] listener = {null};
                //实例化一个地理编码查询对象
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(marker.getPosition());
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        //获取点击的坐标地址
                        button.setText(arg0.getAddress());
                        button.setTextColor(Color.BLACK);
                        button.setWidth(300);

                        listener[0] = new InfoWindow.OnInfoWindowClickListener() {
                            public void onInfoWindowClick() {
                                LatLng ll = marker.getPosition();
                                LatLng llNew = new LatLng(ll.latitude + 0.002,
                                        ll.longitude + 0.002);
                                marker.setPosition(llNew);
                                mBaiduMap.hideInfoWindow();
                            }
                        };
                        LatLng ll = marker.getPosition();
                        mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -47, listener[0]);
                        mBaiduMap.showInfoWindow(mInfoWindow);
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
                if (marker == mMarkerA || marker == mMarkerD) {
                    button.setText("更改位置");
                    button.setTextColor(Color.BLACK);
                    button.setWidth(300);

                    listener[0] = new InfoWindow.OnInfoWindowClickListener() {
                        public void onInfoWindowClick() {
                            LatLng ll = marker.getPosition();
                            LatLng llNew = new LatLng(ll.latitude + 0.002,
                                    ll.longitude + 0.002);
                            marker.setPosition(llNew);
                            mBaiduMap.hideInfoWindow();
                        }
                    };
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -47, listener[0]);
                    mBaiduMap.showInfoWindow(mInfoWindow);
                } else if (marker == mMarkerB) {
                    button.setText("更改图标");
                    button.setTextColor(Color.BLACK);
                    button.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            mBaiduMap.hideInfoWindow();
                        }
                    });
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(button, ll, -47);
                    mBaiduMap.showInfoWindow(mInfoWindow);
                } else if (marker == mMarkerC) {
                    button.setText("删除");
                    button.setTextColor(Color.BLACK);
                    button.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            marker.remove();
                            mBaiduMap.hideInfoWindow();
                        }
                    });
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(button, ll, -47);
                    mBaiduMap.showInfoWindow(mInfoWindow);
                }
                return true;
            }
        });
    }

    private void createTestData(LatLng location) {
        int x;
        int y;
        LatLng latLng = null;
        Random random = new Random();
        mBaiduMap.clear();
        for (int i = 0; i < 40; i++) {
            x = random.nextInt(100) + 10;
            y = random.nextInt(100) + 10;
            switch (i % 4) {
                case 0:
                    latLng = new LatLng(location.latitude + x * 0.0001, location.longitude + y * 0.0001);
                    break;
                case 1:
                    latLng = new LatLng(location.latitude + x * 0.0001, location.longitude - y * 0.0001);
                    break;
                case 2:
                    latLng = new LatLng(location.latitude - x * 0.0001, location.longitude + y * 0.0001);
                    break;
                case 3:
                    latLng = new LatLng(location.latitude - x * 0.0001, location.longitude - y * 0.0001);
                    break;
                default:
                    break;
            }

            MarkerOptions options = new MarkerOptions().position(latLng).icon(icon_dot).zIndex(i);
            mBaiduMap.addOverlay(options);
        }
    }

    public void initOverlay(BDLocation location) {
        // add marker overlay
        LatLng llA = new LatLng(location.getLatitude() - 0.002, location.getLongitude());
        LatLng llB = new LatLng(location.getLatitude() + 0.002, location.getLongitude());
        LatLng llC = new LatLng(location.getLatitude(), location.getLongitude() - 0.002);
        LatLng llD = new LatLng(location.getLatitude(), location.getLongitude() + 0.002);

        MarkerOptions ooA = new MarkerOptions().position(llA).icon(icon_dot)
                .zIndex(9).draggable(true).title("A");
        mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA));
//        MarkerOptions ooB = new MarkerOptions().position(llB).icon(bdB).title("B")
//                .zIndex(5);
//        mMarkerB = (Marker) (mBaiduMap.addOverlay(ooB));
//        MarkerOptions ooC = new MarkerOptions().position(llC).icon(bdC).title("C")
//                .perspective(true).anchor(0.5f, 0.5f).rotate(30).zIndex(7);
//        mMarkerC = (Marker) (mBaiduMap.addOverlay(ooC));
//        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
//        giflist.add(icon_dot);
//        giflist.add(bdB);
//        giflist.add(bdC);
//        MarkerOptions ooD = new MarkerOptions().position(llD).icons(giflist)
//                .zIndex(0).period(10);
//        mMarkerD = (Marker) (mBaiduMap.addOverlay(ooD));
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            public boolean onMarkerClick(final Marker marker) {
                final Button button = new Button(getApplicationContext());
                button.setBackgroundResource(R.mipmap.popup);
                final InfoWindow.OnInfoWindowClickListener[] listener = {null};
                //实例化一个地理编码查询对象
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(marker.getPosition());
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        //获取点击的坐标地址
                        button.setText(arg0.getAddress());
                        button.setTextColor(Color.BLACK);
                        button.setWidth(300);

                        listener[0] = new InfoWindow.OnInfoWindowClickListener() {
                            public void onInfoWindowClick() {
                                LatLng ll = marker.getPosition();
                                LatLng llNew = new LatLng(ll.latitude + 0.002,
                                        ll.longitude + 0.002);
                                marker.setPosition(llNew);
                                mBaiduMap.hideInfoWindow();
                            }
                        };
                        LatLng ll = marker.getPosition();
                        mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -47, listener[0]);
                        mBaiduMap.showInfoWindow(mInfoWindow);
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
                if (marker == mMarkerA || marker == mMarkerD) {
                    button.setText("更改位置");
                    button.setTextColor(Color.BLACK);
                    button.setWidth(300);

                    listener[0] = new InfoWindow.OnInfoWindowClickListener() {
                        public void onInfoWindowClick() {
                            LatLng ll = marker.getPosition();
                            LatLng llNew = new LatLng(ll.latitude + 0.002,
                                    ll.longitude + 0.002);
                            marker.setPosition(llNew);
                            mBaiduMap.hideInfoWindow();
                        }
                    };
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -47, listener[0]);
                    mBaiduMap.showInfoWindow(mInfoWindow);
                } else if (marker == mMarkerB) {
                    button.setText("更改图标");
                    button.setTextColor(Color.BLACK);
                    button.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            mBaiduMap.hideInfoWindow();
                        }
                    });
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(button, ll, -47);
                    mBaiduMap.showInfoWindow(mInfoWindow);
                } else if (marker == mMarkerC) {
                    button.setText("删除");
                    button.setTextColor(Color.BLACK);
                    button.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            marker.remove();
                            mBaiduMap.hideInfoWindow();
                        }
                    });
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(button, ll, -47);
                    mBaiduMap.showInfoWindow(mInfoWindow);
                }
                return true;
            }
        });


    }

    /**
     * 清除所有Overlay
     */
    public void clearOverlay() {
        mBaiduMap.clear();
        mMarkerA = null;
        mMarkerB = null;
        mMarkerC = null;
        mMarkerD = null;
    }

    /**
     * 重新添加Overlay
     */
    public void resetOverlay(BDLocation location) {
        clearOverlay();
        initOverlay(location);
    }


    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {
    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        createTestData(mapStatus.target);
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        // map view 销毁后不在处理新接收的位置
        if (location == null || mMapView == null) {
            return;
        }
        createTestData(new LatLng(location.getLatitude(), location.getLongitude()));
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);
        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
        mLocClient.stop();
    }

    @Override
    public void onConnectHotSpotMessage(String s, int i) {

    }

    public void onReceivePoi(BDLocation poiLocation) {
    }


    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }


    @OnClick({R.id.ivLeft, R.id.tvTitle, R.id.ivRight, R.id.rlScanBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivLeft:
                startActivity(new Intent(MainActivity.this, ActivityMine.class));
                overridePendingTransition(R.anim.push_left_in, 0);
//                if (LoginUtil.isLogin()) {
//                    startActivity(new Intent(MainActivity.this, ActivityMine.class));
//                    overridePendingTransition(R.anim.push_left_in, 0);
//                } else {
//                    startActivity(new Intent(MainActivity.this, ActivityLogin.class));
//                    overridePendingTransition(R.anim.push_left_in, 0);
//                }
                break;
            case R.id.tvTitle:
                break;
            case R.id.ivRight:
                break;
            case R.id.rlScanBtn:
//                Intent intent = new Intent();
//                intent.setClass(MainActivity.this, MipcaActivityCapture.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    String resultStr = data.getStringExtra(KeyValue.DATA);
//                    startActivity(new Intent(this, ActivityBuy.class));
                }
                break;
            default:
                break;
        }
    }
}

